<template>
  <div class='container'>
    <div class="contion">
      <div class="top">{{istitle}}</div>
      <div class="conent">
          <el-form style="padding:0 10px" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="学科：" prop="subjectID">
              <el-select v-model="ruleForm.subjectID" placeholder="请选择"  style="width:400px" @change="xkChange">
                <el-option
                  v-for="item in xklist"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="目录：" prop="catalogID">
                <el-select v-model="ruleForm.catalogID" placeholder="请选择" style="width:400px">
                  <el-option
                    v-for="item in mllist"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="企业：" prop="enterpriseID">
              <el-select v-model="ruleForm.enterpriseID" placeholder="请选择" style="width:400px">
                  <el-option
                    v-for="item in optionlist"
                    :key="item.id"
                    :label="item.company"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            <el-form-item label="城市：" prop="province">
               <el-select
                  style="width: 198px;"
                  v-model="ruleForm.province"
                  placeholder="请选择"
                  @change="changePro"

                >
                  <el-option
                    v-for="item in addressData"
                    :key="item.index"
                    :label="item.index"
                    :value="item"
                     @click.native="add(item)"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 198px; margin-left: 4px;"
                  v-model="ruleForm.city"
                  placeholder="请选择"

                >
                  <el-option
                    v-for="item in cityData"
                    :key="item.index"
                    :label="item.index"
                    :value="item"
                  >
                  </el-option>
                </el-select>
            </el-form-item>
           <el-form-item label="方向：" prop="direction">
              <el-select
                v-model="ruleForm.direction"
                placeholder="请选择"
                style="width:400px">
                <el-option
                  v-for="item in directionlist"
                  :key="item.index"
                  :label="item.index"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="题型:" prop="questionType">
              <el-radio-group v-model="ruleForm.questionType">
                <el-radio :label="'1'">单选</el-radio>
                <el-radio :label="'2'">多选</el-radio>
                <el-radio :label="'3'">简答</el-radio>
              </el-radio-group>
              </el-form-item>
              <el-form-item label="难度:" prop="difficulty">
              <el-radio-group v-model="ruleForm.difficulty">
                <el-radio :label="'1'">简单</el-radio>
                <el-radio :label="'2'">一般</el-radio>
                <el-radio :label="'3'">困难</el-radio>
              </el-radio-group>
              </el-form-item >
           <el-form-item label="题干：" prop="question" style="height:250px;">
              <quillEditor v-model="ruleForm.question" :options="editorOption" style="height: 200px;" placeholder="  " />
            </el-form-item>
            <el-form-item label="选项:" v-if="ruleForm.questionType==='1'||ruleForm.questionType==='2'">
              <div v-for="(item,index) in ruleForm.options" :key="item.code">
                <el-radio-group style="padding-bottom: 20px;" v-model="radio"  v-if="ruleForm.questionType==='1'" @change="change">
                  <el-radio class="erando" :label="index">{{item.code}}: <el-input class="inout" v-model="item.title"/>
                  <el-upload
                  :label="index"
                  style="display: inline-block;"
                  class="upload"
                  action="http://localhost:3000/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" class="img" :src="imageUrl">
                  <div v-else  class="buttun" >点击上传</div>
                  </el-upload>
                  </el-radio>

                </el-radio-group>

                <el-checkbox style="    margin-bottom: 10px;" v-if="ruleForm.questionType==='2'"  v-model="item.isRight">{{item.code}}: <el-input v-model="item.title" />
                 <el-upload
                  style="display: inline-block;"
                  class="upload"
                  action="http://localhost:3000/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" class="img" :src="imageUrl">
                  <div v-else  class="buttun" >点击上传</div>
                  </el-upload>
                </el-checkbox>

              </div>
              <el-button type="danger" size="small"  :disabled="ruleForm.questionType!=='2'" @click="addXuanxiang">+增加选项与答案</el-button>
            </el-form-item>

              <el-form-item label="解析视频：">
              <el-input v-model="ruleForm.videoURL" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="答案解析：" prop="answer" style="height:250px;">
              <quillEditor v-model="ruleForm.answer" class="quill-editor" style="height: 200px;" :options="editorOption" placeholder="  " />
            </el-form-item>
            <el-form-item label="题目备注：">
              <el-input
                type="textarea"
                style="width:400px;"
                :rows="3"
                v-model="ruleForm.remarks">
              </el-input>
            </el-form-item>
              <el-form-item label="试题标签:" >
              <el-select v-model="ruleForm.tags" multiple style="width:400px;" >
                <el-option :value="item.tagName"  v-for="(item,index) in baioqianList " :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">确认提交</el-button>
            </el-form-item>
          </el-form>
      </div>
    </div>

  </div>
</template>

<script>

import { quillEditor } from 'vue-quill-editor'
import { subList as xklist } from '@/api/hmmm/subjects.js'
import { list as bqlist } from '@/api/hmmm/tags.js'
import { list as mllist } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
import { add, detail, update } from '../../api/hmmm/questions'
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
// import { detail } from '@/api/hmmm/directorys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
// console.log(provinces)
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      ruleForm: {
        subjectID: '', // 学科数据
        catalogID: '', // 目录数据
        enterpriseID: '', // 企业数据
        province: '', // 城市数据
        city: '', // 地区数据
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度,
        question: '', // 题干
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签

      },
      // 校验
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true }],
        difficulty: [{ required: true }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入题干', trigger: 'blur' }]

      },
      imageUrl: '',
      content: null,
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        }
      },
      pagelist: {
        page: '1',
        pagesize: '1000'
      },
      radio: '',
      optionlist: [], // 企业
      baioqianList: [],
      company: '',
      xklist: [], // 学科
      mllist: [], // 目录
      addressData: [], // 市
      cityData: [], // 区
      directions: '',
      questionTypelist: [], // 题型
      difficultylist: [], // 难度
      directionlist: [] // 方向
    }
  },
  // 定义计算属性
  computed: {
    istitle () {
      return this.ruleForm.id ? '试题修改' : '试题录入'
    },
    // 获取id
    getId () {
      return this.$route.query.id ? this.$route.query.id : null
    }
  },
  created () {
    this.loadsimple()
    this.changePro()
    this.loadlistget()
    this.directionlist = direction
    this.questionTypelist = questionType
    this.difficultylist = difficulty
    if (!this.getId) return
    this.getDetail(this.getId)
  },
  methods: {
    // 获取基础题库详情
    async getDetail (id) {
      const { data } = await detail({ id })
      this.ruleForm = data
      // console.log(this.ruleForm, 10)
      // this.ruleForm.tags = data.tags.split(',')

      if (this.ruleForm.questionType === '1') {
        this.ruleForm.options.forEach((item, index) => {
          if (item.isRight === 1) {
            this.radio = index
          }
        })
      }

      if (this.ruleForm.questionType === '2') {
        this.ruleForm.options.forEach(item => {
          if (item.isRight === 1) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
      }
    },
    // 单选
    change (num) {
      // console.log(num)
      this.ruleForm.options[num].isRight = true
    },
    zimu () {
      const arr = []
      for (let i = 65, j = 0; i < 91; i++, j++) {
        arr[j] = String.fromCharCode(i)
      }
      // console.log(arr)
      return arr
    },
    // 添加选项
    addXuanxiang () {
      const arr = this.zimu()
      const i = this.ruleForm.options.length
      this.ruleForm.options.push({ isRight: false, code: arr[i], title: '', img: '' })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 学科
    async loadsimple () {
      const res = await xklist(this.pagelist)
      console.log(res)
      this.xklist = res.data.items
    },
    async xkChange (id) {
      this.loadmllist(id)
      const res = await bqlist({ subjectID: id })
      console.log(res)
      this.baioqianList = res.data.items
    },
    async loadmllist (id) {
      const res = await mllist({ subjectID: id })
      console.log(res, '11111111111')
      this.mllist = res.data.items
    },
    // 企业
    async loadlistget () {
      const res = await list()
      // console.log(res)
      this.optionlist = res.data.items
    },
    // 省份更改
    async changePro () {
      const res = await provinces()
      // console.log(res)
      this.addressData = res
      this.ruleForm.city = ''
    },
    // 市更改
    add (city) {
      const res = citys(city)
      // console.log(res)
      this.cityData = res
    },
    submitForm () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        // 转换数据格式
        // console.log(this.ruleForm)
        const tags = this.ruleForm.tags.toString()
        this.ruleForm = { ...this.ruleForm, tags }
        if (this.ruleForm.id) {
          await update(this.ruleForm)
          // console.log(res)
          this.$message.success('修改成功')
        } else {
          // console.log(this.ruleForm)
        // console.log(this.ruleForm)
          await add(this.ruleForm)
          // console.log(res)
          this.$message.success('添加成功')
        }

        // 清空表单
        this.ruleForm = {}
        // 跳转到基础题库
        this.$router.push('/questions/list')
        // 获取基础题库列表
      })
    }

  }
}
</script>

<style scoped lang='scss'>
.erando{
  margin-right: 0;

}
.img{
  width: 100px;
  height: 60px;
  margin-bottom: -23px;
  margin-left: 5px;

}
.inout{
  width: 200px;
}
.upload{
   color: #000;
    width: 100px;
    height: 60px;
    line-height: 60px;
    margin-left: 5px;
}
 .buttun {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
     font-size: 12px;
    color: #000;
    width: 100px;
    height: 60px;
    line-height: 60px;
    cursor: pointer;
  }
  .buttun .upload:hover {
    border-color: #409EFF;
  }
  .container {
    padding: 20px;
    .contion {
      background-color: #fff;
      .top {
        padding: 18px 20px;
        border-bottom: 1px solid #ebeef5;
      }
      .conent {
        padding: 20px;
        .upload-demo {
         display: inline-block;
         width: 100px;
         height: 60px;
         .but {
          width: 100px;
          height: 60px;
          border-radius: 6px;
          margin: 5px;
         }
        }
      }
    }
  }
</style>
